﻿using System;
using System.Web;
using Crosland.Automotriz.Core;
using Crosland.Automotriz.Logic;
using Crosland.Automotriz.Logic.Linq;

using System.Collections.Generic;
using Crosland.Automotriz.Seguridad.Business;
using Crosland.Automotriz.Seguridad.Entity;
using System.Web.UI;
using System.Net.Mail;
using System.Configuration;

namespace Crosland.Automotriz.Web.Seguridad
{
    public partial class Login : System.Web.UI.Page
    {
        LecturaTicketSAP BL_SAP = new LecturaTicketSAP();
        clsUsuarioLogic BL_login = new clsUsuarioLogic();

        protected void Page_Load(object sender, EventArgs e)
        {
           

            if (!IsPostBack)
            {
                this.VerificarEstadoSesion();                
            }
        }

        protected void btnIngresar_Click(object sender, EventArgs e)
        {
        
            this.Logear2();
        }

        protected void VerificarEstadoSesion()
        {
            if (Session[DatosSesion.User] != null)
            {
                Response.Redirect("~/Seguridad/wFrmDefault.aspx");               
            }

            HttpCookie cookie = Request.Cookies[DatosSesion.InicioSesion];

            if (cookie != null)
            {
                if (cookie[DatosSesion.User] != null)
                {
                    Response.Redirect("~/Seguridad/wFrmDefault.aspx");                    
                }
            }
        }
        string des_email="";
        void RecuperaEmail() {

            try
            {
                List<T_SEG_USUARIO> list = BL_login.listaEmail(txtEmail.Text);
                if (list[0].DES_EMAIL == string.Empty)
                {

                }
                else
                {

                    des_email = list[0].DES_EMAIL;

                }

            }
            catch 
            {
                lblMsj.Text = string.Empty;
                lblMsj.Text = "El email ingresado no existe";
                string scriptExeption = "ShowPopupLogin();";
                ScriptManager.RegisterStartupScript(this, typeof(Page), "carga", scriptExeption, true);
             
            }

            

        
        }

        string clave = "";
        void ActualizaClave() { 


         clave=BL_login.GenerarPass(1,8);
         BL_login.actualizarPassword(BL_login.EncriptarPasswordUser(clave), des_email);        
        
        }

        MailMessage mail = new MailMessage();

        void EnviarPasswordNuevo()
        {
            try
            {




                mail.From = new MailAddress(ConfigurationManager.AppSettings["MailFrom"], ConfigurationManager.AppSettings["UserNameSMTP"]);
                mail.To.Add(txtEmail.Text);
                mail.Subject = ("Password Nuevo ");
                mail.Body = ("Su nuevo password es : "+clave);
                SmtpClient s = new SmtpClient();
                s.Host = ConfigurationManager.AppSettings["EmailServer"];
                s.Port = 25;
                s.EnableSsl = false;
                s.UseDefaultCredentials = false;
                s.Credentials = new System.Net.NetworkCredential(ConfigurationManager.AppSettings["MailFrom"], ConfigurationManager.AppSettings["PasswordSMTP"]);
                s.Send(mail);

                lblMsj.Text = string.Empty;
                lblMsj.Text = "Su password ha sido enviado a su email";
                string scriptExeption = "ShowPopupLogin();";
                ScriptManager.RegisterStartupScript(this, typeof(Page), "carga", scriptExeption, true);


            }
            catch
            {
                lblMsj.Text = string.Empty;
                lblMsj.Text = "No se pudo enviar al email por problemas de conexion";
                string scriptExeption = "ShowPopupLogin();";
                ScriptManager.RegisterStartupScript(this, typeof(Page), "carga", scriptExeption, true);

            }




        }

        void RegistrarHistorialLogError() {

            clsT_Seg_Historial_LogLogic clst_seg_historial_log = new clsT_Seg_Historial_LogLogic();
            T_SEG_HISTORIAL_LOG t_seg_historial_log = new T_SEG_HISTORIAL_LOG();
            t_seg_historial_log.ID_SEG_HISTORIAL_LOG = clst_seg_historial_log.UltimoNumeroLog_historial() + 1;
            t_seg_historial_log.ID_USUARIO = txtUsuario.Text;
            t_seg_historial_log.FECHA = DateTime.Now;
            t_seg_historial_log.RESULTADO = false;
            clst_seg_historial_log.Insertar(t_seg_historial_log); 
        
        
        }


        void RegistrarHistoriallogTrue() {

            clsT_Seg_Historial_LogLogic clst_seg_historial_log = new clsT_Seg_Historial_LogLogic();
            T_SEG_HISTORIAL_LOG t_seg_historial_log = new T_SEG_HISTORIAL_LOG();
            t_seg_historial_log.ID_SEG_HISTORIAL_LOG = clst_seg_historial_log.UltimoNumeroLog_historial() + 1;
            t_seg_historial_log.ID_USUARIO = txtUsuario.Text;
            t_seg_historial_log.FECHA = DateTime.Now;
            t_seg_historial_log.RESULTADO = true;
            clst_seg_historial_log.Insertar(t_seg_historial_log);
            Global.id_seg_historial = t_seg_historial_log.ID_SEG_HISTORIAL_LOG;
        
        }



     
        protected void lblRecuperarClave_Click(object sender, EventArgs e)
        {
            this.lblMensaje.Text = "Ingrese el email para enviarle el password.";
            this.pnlMensaje.CssClass = EstilosPagina.CssMensajeMsg;
            this.pnlRecuperar.Visible = true;
            this.pnlLogin.Visible = false;
        }


        void Logear2()
        {
            string username = this.txtUsuario.Text;
            string password = this.txtPassword.Text;


                try
                {
                    string resultado = BL_login.ValidarUsuario(username, password);
                    List<T_SEG_USUARIO> listaUsuario = BL_login.listarUser(username);
                    if (resultado == ResultadoLogin.LoginOk)
                    {
                        Session[DatosSesion.User] = username;
                        Session["User"] = txtUsuario.Text;
                        Session["TipoUsuario"] = listaUsuario[0].ID_TIPO_USUARIO;
                        this.RegistrarHistoriallogTrue();
                        Response.Redirect("wFrmDefault.aspx");
                    }

                    else
                    {


                        this.RegistrarHistorialLogError();
                        lblMsj.Text = string.Empty;
                        lblMsj.Text = "El nombre de usuario o la contraseña que ingresaste es incorrecto.";
                        string scriptExeption = "ShowPopupLogin();";
                        ScriptManager.RegisterStartupScript(this, typeof(Page), "carga", scriptExeption, true);
                    }

                }
                catch (Exception)
                {

                    lblMsj.Text = string.Empty;
                    lblMsj.Text = "El nombre de usuario o la contraseña que ingresaste es incorrecto.";
                    string scriptExeption = "ShowPopupLogin();";
                    ScriptManager.RegisterStartupScript(this, typeof(Page), "carga", scriptExeption, true);

                }
   
          
        }

        protected void btnIngresar_Click1(object sender, EventArgs e)
        {


            Global.wlogin = txtPassword.Text;

            if (txtUsuario.Text == string.Empty)
            {

                lblMsj.Text = string.Empty;
                lblMsj.Text = "Debe ingresar su usuario.";
                string scriptExeption = "ShowPopupLogin();";
                ScriptManager.RegisterStartupScript(this, typeof(Page), "carga", scriptExeption, true);

            }
            else if (txtPassword.Text == string.Empty)
            {



                lblMsj.Text = string.Empty;
                lblMsj.Text = "Debe ingresar su contraseña.";
                string scriptExeption = "ShowPopupLogin();";
                ScriptManager.RegisterStartupScript(this, typeof(Page), "carga", scriptExeption, true);

            }
            else
            {


                this.Logear2();
            }


        }
        public struct ResultadoLogin
        {
            /// <summary>
            /// El login es correcto
            /// </summary>
            public const string LoginOk = "OK";

            /// <summary>
            /// El usuario no existe
            /// </summary>
            public const string LoginUserNoxiste = "seg_user_noexiste";

            /// <summary>
            /// El usuario esta inactivo
            /// </summary>
            public const string LoginUserInactivo = "seg_user_noactivo";

            /// <summary>
            /// El password ingresado no es correcto
            /// </summary>
            public const string LoginPwdIncorrecto = "seg_pws_incorrecto";
        }

        protected void btnRecuperar_Click1(object sender, EventArgs e)
        {
            if (txtEmail.Text.Trim() == string.Empty)
            {
                lblMsj.Text = string.Empty;
                lblMsj.Text = "Ingrese su Email por favor ";
                string scriptExeption = "ShowPopupLogin();";
                ScriptManager.RegisterStartupScript(this, typeof(Page), "carga", scriptExeption, true);
            }
            else
            {

                this.RecuperaEmail();
                if (des_email == string.Empty)
                {
                    lblMsj.Text = string.Empty;
                    lblMsj.Text = "El email ingresado no está registrado";
                    string scriptExeption = "ShowPopupLogin();";
                    ScriptManager.RegisterStartupScript(this, typeof(Page), "carga", scriptExeption, true);

                }
                else
                {
                    this.ActualizaClave();
                    this.EnviarPasswordNuevo();
                    txtEmail.Text= string.Empty;

                }
            }


        }

        protected void btnCancelar_Click1(object sender, EventArgs e)
        {
            this.lblMensaje.Text = "Por favor ingrese usuario y password";
            this.pnlMensaje.CssClass = EstilosPagina.CssMensajeMsg;
            this.pnlLogin.Visible = true;
            this.pnlRecuperar.Visible = false;
        }


    }
}